﻿using ScottPlot.WPF;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TransEchoViewer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        IEPESensor Sensor = new IEPESensor();
        public System.Timers.Timer pollTimer { get; }
        public bool bPause { get; private set; }

        public MainWindow()
        {
            InitializeComponent();
            pollTimer = new System.Timers.Timer(200) { AutoReset = true, Enabled = true };
            pollTimer.Elapsed += PollTimer_Elapsed;
        }

        private void btnOpenSerial_Click(object sender, RoutedEventArgs e)
        {
            Sensor.Begin(txtPortName.Text);
            if(Sensor.Connected)
            {
                MessageBox.Show("启动成功");
                btnOpenSerial.IsEnabled = false;
            }
        }

        private void PollTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.Dispatcher.Invoke(UpdateUi);
        }

        private void UpdateUi()
        {
            double[] curveArray;
            lock (Sensor.dataLock)
            {
                curveArray = Sensor.DataSeries.ToArray();
            }
            RefreshCurve(plotCurve, curveArray);
        }

        private void RefreshCurve(WpfPlot scot_plot, double[] curve)
        {
            if (bPause)
                return;

            scot_plot.Plot.Clear();
            int cnt = 0;
            var t = curve.Select( c => cnt++).ToArray();
            scot_plot.Plot.Add.SignalXY(t, curve.ToArray()).LineWidth = 2;
            //scot_plot.Plot.Axes.AutoScale();
            scot_plot.Refresh();
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            bPause = true;
        }

        private void btnResume_Click(object sender, RoutedEventArgs e)
        {
            bPause = false;
        }

        private void btnCloseSerial_Click(object sender, RoutedEventArgs e)
        {
            Sensor.Stop();
            btnOpenSerial.IsEnabled = true;
        }

        private void btnAutoScale_Click(object sender, RoutedEventArgs e)
        {
            plotCurve.Plot.Axes.AutoScale();
        }
    }
}
